package com.gobi.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 无sentinel控制台搭建
 *
 * 定义资源和限流规则
 * 使用SphU.entry("Hello")
 */
@RestController
@RequestMapping("n")
public class NoDashBoardController {


    public static final String Resource_HELLO_123 = "hello123";

    @GetMapping("/hello")
    public String hiResttemplate() {

        //1.进行限流控制
        Entry entry = null;
        try {//限流入口
            entry = SphU.entry(Resource_HELLO_123);
            return "Hello Sentinel!";//被保护的资源
        } catch (BlockException e) {
            e.printStackTrace();
            return "系统繁忙，请稍候";//被限流或者降级的处理
        } finally {
            if (null != entry) {
                entry.close();
            }
        }
    }


    /**
     * 定义限流规则
     *
     * @PostConstruct ：在构造函数执行完毕后执行
     */
    @PostConstruct
    public void initFlowRules() {
        //1.创建存放“限流规则”的集合
        List<FlowRule> rules = new ArrayList<FlowRule>();
        //2.创建限流规则
        FlowRule rule = new FlowRule();
        //定义资源
        rule.setResource(Resource_HELLO_123);

        //定义限流规则类型,RuleConstant.FLOW_GRADE_QPS：OPS类型
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //定义OPS每秒最多只能通过的请求个数
        rule.setCount(2);
        rules.add(rule);

        // 3.加载限流规则
        FlowRuleManager.loadRules(rules);


        //定义降级规则
        DegradeRule degradeRule = new DegradeRule();
        degradeRule.setResource(Resource_HELLO_123);
        degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
        degradeRule.setCount(0.01);

        //触发降级，接下的10秒窗口内，会自动降级
        degradeRule.setTimeWindow(10);
        DegradeRuleManager.loadRules(Collections.singletonList(degradeRule));
    }
}
